package admin

import (
	"context"
	"errors"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type SpecValueSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewSpecValueSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SpecValueSaveLogic {
	return &SpecValueSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SpecValueSaveLogic) SpecValueSave(req *types.SpecValueSaveReq) (resp string, err error) {
	specKey := &models.SpecKey{}
	if !utils.GetDataById(req.SpecKeyID, specKey) {
		return "", errors.New("规格配置不存在")
	}

	data := &models.SpecValue{
		SpecKeyID:      req.SpecKeyID,
		SpecTemplateID: specKey.SpecTemplateID,
		Value:          req.Value,
	}
	result := utils.GetData(data)

	if req.Id == 0 {
		if result {
			return "", errors.New("规格值已存在")
		}
		err = utils.InsertData(data)
	} else {
		if result && req.Id != data.ID {
			return "", errors.New("规格值已存在")
		}
		err = utils.UpdateById(req.Id, data)
	}

	if err != nil {
		return "", err
	}

	return "操作成功", nil
}
